<?php

class FeedsController extends ControllerBase
{
    public function listAction()
    {
        //if(!$this->request->isPost()) die('Not a post');
        $user_id = $this->session->get('user_id');
        $page_no = htmlentities(strip_tags($this->request->getPost('page_no')));
     //   $page = 0;
        $result = array();

        $data = UserFeedsTb::listFeeds($user_id);
        
        $paginator = new \Phalcon\Paginator\Adapter\Model(
            array(
                "data" => $data,
                "limit"=> 5,
                "page" => $page_no
            )
        );

        // Get the paginated results
        $page = $paginator->getPaginate();
        if($page_no > $page->total_pages)
        {
            $result  = [];
            echo json_encode($result);
            $this->view->disable();
            exit();
        } 
        foreach ($page->items as $value) {
            $result[] = array(
                    "date_created"=>$value->uft->date_created,
                    "feed_container"=>htmlentities($value->uft->feed_container),
                    "feed_id"=>$value->uft->id,
                    "feed_title"=>nl2br($value->uft->feed_title),
                    "feed_type"=>$value->uft->feed_type,
                    "fullname"=>$value->uat->fname.' '.$value->uat->lname,
                    "prof_pic"=>$value->uat->profile_pic,
                    "sender_fullname"=>UserAccountTb::getFullName($value->uft->user_id),
                    "sender_id"=>$user_id,
                    "user_id"=>$value->uft->user_id,
                    "type"=>gettype($page)
                );        
        }    
        echo json_encode($result);
        $this->view->disable();


    }

    public function updateTotalPostsAction()
    {
        $data = $this->request->getPost('user_id');
        echo UserFeedsTb::countPosts($data);
        $this->view->disable();
    }

    public function pushAction()
    {

        $pusher = new Pusher(PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_ID);
        $pusher->trigger('my-channel', 'my-event', array( 'message' => 'hello world'));
        //var_dump($pusher);
        $this->view->disable();

    }
    public function indexAction()
    {
        $this->view->setVar('title', 'Behomebased');

    	if($this->session->get('user_id') == null) $this->response->redirect(BASE_URI);
		
        $user_id = $this->session->get('user_id');

        $feeds = UserFeedsTb::listFeeds($user_id);
        
        $paginator = new \Phalcon\Paginator\Adapter\Model(
            array(
                "data" => $feeds,
                "limit"=> 5,
                "page" => 1
            )
        );

        // Get the paginated results
        $page = $paginator->getPaginate();


        $info = UserAccountTb::findFirstById($user_id);
        if($info == false)
        {
            header("Location: ".BASE_URI);
        }
        else
        {
            if($info->activated == 0)
            {
              header("Location: ".BASE_URI.'registration/confirm?ea='.$info->email);
            }
        }
        
        $possible_connections = UserConnectionsTb::listPossibleConnection($user_id);


        $this->view->setVar('page_no',1);
        $this->view->setMainView('index');
        $this->view->setVar('page_name', 'Feeds');
        $this->view->setVar('content', 'feeds/index');
        $this->view->setVar('feeds',$page->items);
        $this->view->setVar('info',$info);
        $this->view->setVar('possible_connections',$possible_connections);

    }


    public function convertAction()
    {
        

        $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

        $text = $_GET['text'];
        
        $result = array();

        if(preg_match($reg_exUrl, $text, $url))
        {
            $info = $this->getUrlInfo($url[0]);

            $title  = "<a target='_blank' href='" . $url[0] . "'>" ."<h5>" . $info['title'] . "</h5>";
            $content = "<h6>" . $info['content'] . "</h6>" . "</a>";

            $result['html'] = $title.$content;
            $result['status'] = true;
        }
        else
        {
            $result['status'] = false;
        } 
       
        echo json_encode($result);
        $this->view->disable();


    }


// status update
    public function insertAction()
    {

        $info = UserAccountTb::findFirstById($this->session->get('user_id'));

        $result = array();
        $feed_type = ($this->session->get('user_id') == $_POST['receiver']) ? "status_update" : "wall_posts";
        
        $data = array(
            'user_id'=>$_POST['receiver'],
            'feed_title'=>nl2br($_POST['content']),
            'feed_container'=>html_entity_decode($_POST['html']),
            'feed_type'=> $feed_type,
            'fullname' => $info->fname.' '.$info->lname,
            'prof_pic' => $info->profile_pic,
            'sender_id' => $this->session->get('user_id'),
            'sender_fullname' => UserAccountTb::getFullname($_POST['receiver'])
            );

        $feeds = new UserFeedsTb();
        if($feeds->save($data) == false){
            $result['status'] = false;
            $messages= '';
            foreach ($feeds->getMessages() as $value) {
                $messages.=$value.'<br>';
                # code...
            }
            $result['messages'] = $messages;

        }
        else
        {
            $result['status'] = true;
            $data['feed_id'] = $feeds->id;
            $data['date_created'] = $feeds->date_created;
            switch($data['feed_type'])
            {
                case 'wall_posts':
                    Notification::saveWallPost($data['user_id'],json_encode($data));
                break;
            }
            
            $pusher = new Pusher(PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_ID);
            $pusher->trigger('my-channel', 'status-update', $data);
           // $pusher->trigger('my-channel', 'update-total-posts', $data);
    
        }
        echo json_encode($result);        
        
        $this->view->disable();
    }

   public function getTitle($Url)
   {
      $str = file_get_contents($Url);
      if(strlen($str)>0)
      {
          preg_match("/\<description\>(.*)\<\/description\>/",$str,$title);
          return $title;
      }
   }

   public function getUrlInfo($url)
   {
       $get_url = $url; 
        
        //Include PHP HTML DOM parser (requires PHP 5 +)
        
        //get URL content
        $get_content = file_get_html($get_url); 
        
        //Get Page Title 
        foreach($get_content->find('title') as $element) 
        {
            $page_title = $element->plaintext;
        }
        
        //Get Body Text
        foreach($get_content->find('body') as $element) 
        {
            $page_body = trim($element->plaintext);
            $pos=strpos($page_body, ' ', 200); //Find the numeric position to substract
            $page_body = substr($page_body,0,$pos ); //shorten text to 200 chars
        }
    
        $image_urls = array();
        
        //get all images URLs in the content
        foreach($get_content->find('img') as $element) 
        {
                /* check image URL is valid and name isn't blank.gif/blank.png etc..
                you can also use other methods to check if image really exist */
                if(!preg_match('/blank.(.*)/i', $element->src) && filter_var($element->src, FILTER_VALIDATE_URL))
                {
                    $image_urls[] =  $element->src;
                }
        }
        
        //prepare for JSON 
        $output = array('title'=>$page_title, 'images'=>$image_urls, 'content'=> $page_body);
        return $output; //output JSON data
   }

}

